package com.huike.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huike.entity.Department;
import com.huike.entity.Employee;
import com.huike.mapper.EmpRoleMapper;
import com.huike.mapper.EmployeeMapper;
import com.huike.query.EmployeeQuery;
import com.huike.query.LoginQuery;
import com.huike.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmpRoleMapper empRoleMapper;

    @Override
    public Employee login(LoginQuery lq) {
        Employee dbUser = employeeMapper.getEmployeeByUsername(lq.getUsername());
        if(dbUser == null){
            return null;
        }
        //判断密码是否正确
        String queryPassword = SecureUtil.md5(lq.getPassword());
        if(queryPassword.equals(dbUser.getPassword())){
            return dbUser;
        }
        return null;
    }

    @Override
    public PageInfo<Employee> getPage(EmployeeQuery eq) {
        //1.查询数据之前调PageHelper.startPage()
        PageHelper.startPage(eq.getCurrentPage(),eq.getPageSize());
        //2.数据库查询
        List<Employee> all = employeeMapper.getAll(eq);
        //3.将查询的结果放到PageInfo里
        return new PageInfo<>(all);
    }

    @Override
    @Transactional
    public void saveOrUpdate(Employee employee,Long[] roleIds) {
        //密码入库时应该md5
        if(employee.getPassword()!=null)
        {
            employee.setPassword(SecureUtil.md5(employee.getPassword()));
        }
            //1.保存或更新employee
            employeeMapper.saveOrUpdate(employee);
            //2.删除关于emp关联的角色
            Long empId = employee.getId();
            empRoleMapper.deleteByEmpId(empId);
            //3.插入所有新的emp-role关系
            if(roleIds!=null){
                empRoleMapper.addRelations(empId,roleIds);
            }

    }

    @Override
    public Employee getEmpById(Integer id) {
        return employeeMapper.getEmpById(id);
    }

    @Override
    public int deleteById(Long id) {
        return employeeMapper.deleteById(id);
    }

}
